package com.ymy.thinking.in.spring.bean.instance;

import com.ymy.thinking.in.spring.bean.factory.DefaultPersonFactory;
import com.ymy.thinking.in.spring.bean.factory.PersonFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 特殊的 Bean 实例化
 *
 * @author Ringo
 * @date 2021/8/25 21:54
 */
public class BeanSpecialInstanceDemo {

    public static void main(String[] args) {
        // 创建 IoC 容器
        String configLocation = "classpath:META-INF/special-bean-instance-context.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configLocation);

        // 依赖查找
        ServiceLoader<PersonFactory> serviceLoader = applicationContext.getBean("personFactoryServiceLoader", ServiceLoader.class);

        System.out.println("== Java ServiceLoader ==");
        display(serviceLoader);

        System.out.println("== Spring ServiceLoaderFactoryBean ==");
        serviceLoaderDemo();
    }

    public static void serviceLoaderDemo() {
        // 加载 接口 和 实现类
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ServiceLoader<PersonFactory> serviceLoader = ServiceLoader.load(PersonFactory.class, classLoader);
        display(serviceLoader);
    }

    public static void display(ServiceLoader<PersonFactory> serviceLoader) {
        // 迭代输出实现类
        // 定义多个相同的实现类会自动去重
        Iterator<PersonFactory> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
